package org.replay.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.Properties;

/*
 * Copyright © 2020 lizicong,All rights reserved.
 *
 * Licensed under the GPL License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * 连接NACOS,获取配置信息
 * @author lizicong
 */
@Configuration
public class NacosGetCfgConfiguration {

    @Value("${nacos.cfg.host}")
    String serverAddr;
    @Value("${nacos.cfg.data.id}")
    String dataId;
    @Value("${nacos.cfg.group.id}")
    String group;
    @Value("${nacos.cfg.app.type}")
    String activationType;

    /**
     * @return 从nacos拉取下来的JSON格式的配置信息
     * @throws Exception 不想处理~
     */
    @Bean("nacos-cfg")
    public JSONObject getConfig() throws Exception {
        System.out.println(">>>>>>>>>>>"+dataId);
        System.out.println(">>>>>>>>>>>"+serverAddr);

        //组装服务器目标配置信息
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);

        //生成nacos client客户端
        ConfigService configService = NacosFactory.createConfigService(properties);

        //从nacos获取到的配置信息
        String seckillCfg = configService.getConfig(dataId, group, 5000);

        //解析JSON
        JSONObject jsonObject = JSON.parseObject(seckillCfg);

        //获取该工程配置组
        return jsonObject.getJSONObject(activationType);

    }

}
